package edu.nf.ch04.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

/**
 * @author CSY
 * @date 2025 - 04 - 22
 */
public class MybatisUtils {
    /**
     * 声明一个SqlSessionFactory工厂 - 用于创建SqlSession
     */
    private static SqlSessionFactory sqlSessionFactory;

    /**
     * 在类加载时就完成初始化 - 静态代码块
     */
    static{
        try {
            //读取mybatis配置文件，返回一个输入流
            InputStream is = Resources.getResourceAsStream("mybatis.xml");
            //通过SqlSessionFactoryBuilder类来解析流的数据并初始化
            sqlSessionFactory = new SqlSessionFactoryBuilder()
                    .build(is);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 默认为自动提交事务的
     * @return
     */
    public static SqlSession getSqlSession(){
        return sqlSessionFactory.openSession(true);
    }

    /**
     * 创建SqlSession对象
     * 如果autoCommit为true则为自动提交事务，false为手动提交
     * @param autoCommit 是否自动提交Change access modifier
     * @return
     */
    public static SqlSession getSqlSession(boolean autoCommit){
        return sqlSessionFactory.openSession(autoCommit);
    }
}
